import 'package:flutter/cupertino.dart';
import 'package:flutter_massage/common_lib/http/index.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/pages/model/bean.dart';
import 'package:flutter_massage/pages/technician/technician_detail/technician_detail_page.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:get/get.dart';

class HomeLogic extends GetxController {
  List<HomeBannerBean> bannerList = [];
  List<TechnicianBean> technicianList = [];
  List<ProjectBean> projectList = [];

  final ValueNotifier<String> address = ValueNotifier('');

  @override
  void onReady() async {
    super.onReady();

    CommonObservable().addObserver(TechnicianDetailPage.keyListener, refreshPage);

    CommonJson.getHomeData((value) async {
      bannerList = await CommonJson.getList(
        value,
        (json) => HomeBannerBean.fromJson(json),
        keyName: 'banner',
      );

      technicianList = await CommonJson.getList(
        value,
        (json) => TechnicianBean.fromJson(json),
        keyName: 'technicians',
      );

      projectList = await CommonJson.getList(
        value,
        (json) => ProjectBean.fromJson(json),
        keyName: 'items',
      );

      _refresh();
    });

    Future.delayed(const Duration(seconds: 1), () async {
      address.value = await LocationService.instance.address();
    });
  }

  @override
  void onClose() {
    super.onClose();
    CommonObservable().removeObserver(TechnicianDetailPage.keyListener, refreshPage);
  }

  void refreshPage(key, [value]) {
    _refresh();
  }

  void _refresh() {
    List blackList = GetStorageService.blackList();
    for (var value in blackList) {
      technicianList.removeWhere((element) => element.id == value);
    }
    update();
  }

  var currentIndex = 0.obs;

  void onPageChanged(int index) => currentIndex.value = index;
}
